<?php
set_time_limit(0);

$dir = '/var/music/';
$incomingDir = $dir . 'INCOMING/';
$outgoingDir = $dir . 'UNSORTED/';
   
include_once('./includes/getid3/getid3/getid3.php');

//the loadTrkFileInfo() function inputs two strings, full string paths 
//to the incoming directory (where scanned files are) and outgoing directory (where they will be moved to).
//
//this function scans all the files in a directory and loads them into a 3-part array:
// 0. tracks that already exist in the DB
// 1. albums that already exist in the DB, but tracks that do not.
// 2. no track or album of this description seems to be in the DB 
function loadTrkFileInfo ($incomingDir = '/var/music/INCOMING/', $outgoingDir = '/var/music/UNSORTED/') {
//   $filearr = array();
   $i = 0; // iterator
   
   // this array contains filetypes we consider valid
   $fileTypes = array('mp3','ogg','wmv','asf','flac','wma','wav'); // for now, m4a doesn't seem to work... 
   
   // initialize a new getID3 object
   $getID3 = new getID3;
   if ($handle = opendir($incomingDir)) {
      // search the directory recurively 
      while (false !== ($file = readdir($handle))) {
         // if a the file appears as "." or "..", it's a directory and we'll get infinite loops, so screen them out
         if ($file != '.' && $file != '..' && !is_dir($incomingDir.$file)) {
	         
            // look for the file in accepted filetypes array
            $ext = strtolower(array_pop(explode(".",$file)));
            if(in_array($ext,$fileTypes)) {
//               $fileSize = filesize($incomingDir.$file);

               // use getid3's analyze function to examine the incoming file 
               $trackInfo = $getID3->analyze($incomingDir.$file);
               
               // getid3's CopyTagsToComments function can take the snagged metadata and put it into an array marked as 'comments_html'
               getid3_lib::CopyTagsToComments($trackInfo);

               // put the relevant comments_html array data into a simpler array called $trkFile, which we'll use throughout the program 
               $trkFile[$i]['title'] = (isset($trackInfo['comments_html']['title'][0]) ? $trackInfo['comments_html']['title'][0] : "");
               $trkFile[$i]['artist'] = (isset($trackInfo['comments_html']['artist'][0]) ? $trackInfo['comments_html']['artist'][0] : "");
               $bitrate = explode(".",($trackInfo['audio']['bitrate']/1000));
               $trkFile[$i]['bitrate'] = $bitrate[0]."k";
               $trkFile[$i]['playtime'] = $trackInfo['playtime_string'];
               $trkFile[$i]['genre'] = (isset($trackInfo['comments_html']['genre'][0]) ? $trackInfo['comments_html']['genre'][0] : "");
               if ($ext == 'ogg' || $ext == 'flac' || $ext == 'm4a') {
                  $trkFile[$i]['num'] = (isset($trackInfo['comments_html']['tracknumber'][0]) ? $trackInfo['comments_html']['tracknumber'][0] : "");
               } else {
                  $trkFile[$i]['num'] = (isset($trackInfo['comments_html']['track'][0]) ? $trackInfo['comments_html']['track'][0] : "");
               }
               $trkFile[$i]['album'] = (isset($trackInfo['comments_html']['album'][0]) ? $trackInfo['comments_html']['album'][0] : "");
               $trkFile[$i]['filepath'] = (isset($trackInfo['filepath']) ? $trackInfo['filepath'] : "");
               $trkFile[$i]['filename'] = (isset($trackInfo['filename']) ? $trackInfo['filename'] : "");
               $trkFile[$i]['ext'] = $ext;
     	         $trkFile[$i]['filesize'] = filesize($incomingDir.$file);
     	         $i++;
            }
         }
         // if item is a directory re-run the function to deep scan and grab lower level files...burrito
         else if(is_dir($incomingDir.$file)) {
            if ($file != "." && $file != "..") {
               $subDir = $incomingDir.$file;
               loadTrkFileInfo($subDir."/");
            }
         }
      }
      closedir($handle);
   }
   ?><pre><?php 
//   var_dump($trkFile);
   ?></pre>
   <?php
   $trkFile = sortTracks($trkFile);
   
//   $loadTrkFileInfo[addTrkAndAlb] = $addTrkAndAlb;
//   $loadTrkFileInfo[TrkDbExists] = $addTrkToAlb;
   return $trkFile;
}


function sortTracks ($trkFile) {
?><pre><?php
var_dump($trkFile);?></pre><?php

   $i = 0; // iterator for each file. 
   $j = 0; // iterator for each album in the $alb array
   $alb = array(); //this array will hold the names of albums scanned.
   
//   foreach ($trkFile as $trk) {
   for ($i = 0; $i < count($trkFile); $i++) {
      unset($albExists);
      for ($k = 0;$k < count($alb); $k++) {
         // if there's a match, then it seems the album is already in the array;
         if ($alb[$k][album] === strtolower($trkFile[$i][album]) && $alb[$k][album]) {
            //echo('<h2>we would have skipped this track because it already exists in the array</h2>');
            $trkFile[$i][albId] = $alb[$k][albId];
            $albExists = true;
         }
      }
      if (!$albExists) {
//?         $trkFile[$i][albId] = $j;
         // {{{ Here goes an SQL query to check for an existing CD; if exists, return the result, if not, check harder, if still no match, return nothing.}}}
         
         //test to see if any matches were returned for the file info from the DB; if not, flag for creation of a new record.
         if ($albDbRecord) {
            // {{{here, we'll append the cdid of the existing db record}}}
            
            // flag the file as having an existing album if it has one 
            $trkFile[$i][match] = 'album';
            
            // next, check to see if there's a track match, and flag if necessary.
            // {{{code goes here}}}
            
         } else {
            // since there was no match, we'll flag this album as a new entry for the DB
            $trkFile[$i][match] = 'none';
            $trkFile[$i][albId] = $j;
            $alb[$j][albId] = $j;
         }
         $alb[$j][album] = strtolower($trkFile[$i][album]);
         $j++;
      }
   }
   ?><pre><?php
   var_dump($alb);
//   var_dump($trkFile);
   if ($trkFile) {
      foreach ($trkFile as $trk) {
         echo($trk[album].' ('.$trk[albId].')<br />');
      }
   } 
   return $trkFile;
}


// sanitizeAndMove() function
//
// Description: 
// This function moves files from the "incoming" directory to the outgoing directory,
// changing names and creating folders as appropriate (to have a consistent naming system)
// 
// inputs:
// 1. the existing file name
// 2. an array with file information/metadata
// 3. destination directory 
//
// Outputs:
// 1. returns 'true' if the actions are completed; otherwise false (or is it null?) 
// 
function sanitizeAndMove ($oldFile, $fileInfo, $outgoingDir = '/var/music/UNSORTED/') {   
   
   //set umask properly so that chmodding works properly in all configurations
   $old_umask = umask(0);
   
   //sanitize album, artist, and title
   $artist = str_replace('/', '-', $fileInfo['artist']);
   $album = str_replace('/', '-', $fileInfo['album']);
   $title = $fileInfo['num'] . ' - ' .str_replace('/', '-', $fileInfo['title']) . '.' . $fileInfo['ext'];
   
   //check if directory exists, if not, add it
   if (!is_file($outgoingDir.$artist.'/'.$album.'/'.$title)) {
      if (!is_dir($outgoingDir.$artist.'/'.$album)) {
         if (!is_dir($outgoingDir.$artist)) mkdir($outgoingDir.$artist, 0777);
         mkdir($outgoingDir.$artist.'/'.$album . '/', 0777);
      }
   }
   //format the title to make it work for a filename 
   $newFilename = $outgoingDir.$artist.'/'.$album.'/'.$title;
   if (rename($oldFile, $newFilename)) $success = true;
   else $success = false;
   
   //set umask back to what it was just in case.
   umask($old_umask);
   
   return $success;
}


if ($do == 'scanFiles') {
   $trk = loadTrkFileInfo();
   ?>
   <form method="post">
   <?php
//   $i = 0; // iterator
   /* if ($addTrkToAlb) {
      echo ('<h3>these tracks will be added to existing albums</h3>');
         foreach ($addTrkToAlb as $trk) {
            echo (
	    '<input type="checkbox" checked="checked" name="trkAppend['.$i.'][execute]" value="true" /><input type="hidden" name="trkAppend[' . $i . '][title]" value="' . $trk['title'] .
	    '" /><input type="hidden" name="trkAppend[' . $i . '][album]" value="' . $trk['album'] . 
	    '" /><input type="hidden" name="trkAppend[' . $i . '][num]" value="' . $trk['num'] . 
	    '" /><input type="hidden" name="trkAppend[' . $i . '][artist]" value="' . $trk['artist'] . 
	    '" /><input type="hidden" name="trkAppend[' . $i . '][playtime]" value="' . $trk['playtime'] . 
	    '" /><input type="hidden" name="trkAppend[' . $i . '][genre]" value="' . $trk['genre'] . 
	    '" /><input type="hidden" name="trkAppend[' . $i . '][bitrate]" value="' . $trk['bitrate'] . 
	    '" /><input type="hidden" name="trkAppend[' . $i . '][ext]" value="' . $trk['ext'] . 
	    '" /><input type="hidden" name="trkAppend[' . $i . '][filepathname]" value="' . $trk['filepath'] . '/' . $trk['filename'] . 
	    '" />'
	    . $trk['title'] . '<br />' ."\n");
	    $i++;
         }
      } */

      for ($i = 0; $i < count($trk); $i++) {
         echo (
	      '<input type="checkbox" checked="checked" name="trk['.$i.'][execute]" value="true" 
	      /><input type="hidden" name="trk['.$i.'][title]" value="'.$trk[title].'" 
	      /><input type="hidden" name="trk['.$i.'][album]" value="'.$trk[$i][album].'" 
	      /><input type="hidden" name="trk['.$i.'][num]" value="'.$trk[$i][num].'" 
	      /><input type="hidden" name="trk['.$i.'][artist]" value="'.$trk[$i][artist].'" 
	      /><input type="hidden" name="trk['.$i.'][playtime]" value="'.$trk[$i][playtime].'" 
	      /><input type="hidden" name="trk['.$i.'][genre]" value="'.$trk[$i][genre].'" 
	      /><input type="hidden" name="trk['.$i.'][bitrate]" value="'.$trk[$i][bitrate].'" 
	      /><input type="hidden" name="trk['.$i.'][ext]" value="'.$trk[$i][ext].'" 
	      /><input type="hidden" name="trk['.$i.'][albId]" value="'.$trk[$i][albId].'" 
	      /><input type="hidden" name="trk['.$i.'][filepathname]" value="'.$trk[$i][filepath].'/'.$trk[$i][filename].'" 
	      />'.$trk[$i]['title'].'<br />'."\n");
      }
//         echo ('<h3>these tracks and albums will be added to the DB</h3>');
//         foreach ($addTrkAndAlb as $trk) {
//            echo ('<input type="hidden" name="trkAdd[' . $i++ . '][title]" value="' . $trk['title'] . '" />' . $trk['title'] . '<br />' . "\n");
//         }
//      }
      $i = 0;
      if ($trkPresent) {
         echo ('<h3>these tracks are already in the DB with files</h3>');
         foreach ($trkPresent as $trkReplace) {
	         echo ($trkReplace['title'] . '<br />');
         }
      }
   ?>
      <input type="hidden" name="do" value="importFiles" />
      <input type="submit" value="Import into DB!" />
      </form>
      <?php
} elseif ($do == 'importFiles') {
   echo('we would have just done all the importing...<br />');
   if ($_POST['trk']){
      foreach ($_POST['trk'] as $trk) {
         echo($trk['artist'] . ' - ' . $trk['num'] . '. ' . $trk['title'] . ' [' . $trk['album'] . ']' . '<br />');
         if ($trk['execute'] == 'true') {
            sanitizeAndMove ($trk['filepathname'], $trk);
//	    addToDb ($trk);
         }
      }
   }
   echo("<br /><h3>These were added anew!</h3>");
   if ($_POST['trkAdd']) {
      foreach ($_POST['trkAdd'] as $trk) {
//         if ($trk['execute'] == 'true') {
            sanitizeAndMove ($trk['filepathname'], $trk);
            addToDb ($trk);
            echo('' . $trk['title'] . '<br />');
//         }
      }
   }
} else {
?>
<form method="post">
Enter Folder:<br>
(use forward slashes and make sure you have a trailing slash on the end ex: c:/path/to/files/ )<br>
<input type="text" name="rootDir"><br>
<input type="submit" value="Scan New Music Files!">
<input type="hidden" name="do" value="scanFiles" /></form>
<?php
}
   ?></pre><?
?> 